/*
 * Copyright (c) 2011 Anthony Vandikas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "stdafx.h"
#include "DatabaseInventory.h"

DatabaseInventory::DatabaseInventory()
{
	database = createDatabase("inventory", "name TEXT, number INTEGER");
}

DatabaseInventory::~DatabaseInventory()
{
	database.close();
}

void DatabaseInventory::addItems(const QList<Item> &items)
{
	// TODO: Refactor this crap.
	QStringList queryItems;
	foreach (auto item, items)
	{
		auto name = item.getName();
		auto number = item.getNumber();

		queryItems << "SELECT ?, ? WHERE NOT EXISTS (SELECT * FROM inventory WHERE name = ? AND number = ?)";
	}

	QSqlQuery query("INSERT OR IGNORE INTO inventory " + queryItems.join(" UNION "), database);
	foreach (auto item, items)
	{
		query.addBindValue(item.getName());
		query.addBindValue(item.getNumber());
		query.addBindValue(item.getName());
		query.addBindValue(item.getNumber());
	}

	query.exec();

	emit modified();
}

void DatabaseInventory::removeItems(const QList<Item> &items)
{
	QStringList queryItems;
	QList<QVariant> queryParameters;

	foreach (auto item, items)
	{
		auto name = item.getName();
		auto number = item.getNumber();

		queryItems << "name = ? AND number = ?";
		queryParameters << name << number;
	}

	QSqlQuery query("DELETE FROM inventory WHERE " + queryItems.join(" OR "), database);
	foreach (auto parameter, queryParameters)
		query.addBindValue(parameter);
	query.exec();

	emit modified();
}

QList<Item> DatabaseInventory::getItems() const
{
	QSqlQuery query("SELECT * FROM inventory", database);
	query.exec();

	QList<Item> output;
	while (query.next())
	{
		auto record = query.record();
		auto name = record.value("name").toString();
		auto number = record.value("number").toInt();

		output << Item(name, number);
	}

	return output;
}